<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <input type="text" placeholder="请输入账号" name="username" />
      <input type="text" placeholder="邮箱" name="email" />
      <input type="text" placeholder="电话号码" name="tel" />
      <input type="submit" value="提交" />
    </div>
    <div class="card"></div>
    <script>
      //获取dom元素
      let username = document.querySelector('[name="username"]');
      let email = document.querySelector('[name="email"]');
      let tel = document.querySelector('[name="tel"]');
      let submitButton = document.querySelector('[type="submit"]');
      //目标渲染对象
      let card = document.querySelector(".card");
      //进入local的对象
      let userList = obserVer({
        username: "",
        email: "",
        tel: "",
      });

      console.log(userList);
      function handelSubmit() {
        let _username = username.value;
        let _email = email.value;
        let _tel = tel.value;

        //每次点击将输入完的value值存入userList对象
        userList.username = _username;
        userList.email = _email;
        userList.tel = _tel;
        //执行相应函数

        //每次执行完清空input的value
        _username = "";
        _email = "";
        _tel = "";
      }
      //该函数处理代理

      function obserVer(userList) {
        //从local获取缓存
        let storege = JSON.parse(localStorage.getItem("username") || "{}");
        //返回对象
        let retObj = {};
        //循环
        for (const key in storege) {
          //如果userlist没有值 就从缓存里取数据赋值
          if (!userList[key]) {
            userList[key] = storege[key];
          }
        }

        for (const key in userList) {
          (function (key) {
            Object.defineProperty(retObj, key, {
              get() {
                return userList[key];
              },
              set(value) {
                userList[key] = value;
                //存入本地数据
                localStorage.setItem("username", JSON.stringify(userList));
                initDom(userList, card);
              },
            });
          })(key);
        }
        initDom(userList, card);
        function initDom(userList, card) {
          card.innerHTML = `
          <h1><span>${userList.username || "未录入"}</span></h1>
          <h2><span>${userList.email || "未录入"}</span></h2>
          <h3><span>${userList.tel || "未录入"}</span></h3>
          `;
        }

        return retObj;
      }

      //绑定事件
      submitButton.addEventListener("click", handelSubmit, false);
    </script>
  </body>
</html>
